<template>
  <a-row :gutter="[16, 16]" class="search">
    <a-col :span="4">
      <a-input v-model:value="searchInfo.content" placeholder="树洞文章" />
    </a-col>
    <a-col :span="4">
      <a-date-picker
        v-model:value="searchInfo.time"
        placeholder="发布日期"
        style="width: 100%"
      />
    </a-col>
    <a-col :span="4" class="btn">
      <a-button :icon="h(SearchOutlined)" type="primary" @click="search"
        >搜索
      </a-button>
      <a-button :icon="h(RedoOutlined)" @click="restSearch">重置</a-button>
    </a-col>
  </a-row>

  <a-row style="display: flex; align-items: center; gap: 15px; margin: 15px 0">
    <a-button type="primary" @click="addOrEdit('add')">新增</a-button>
    <a-popconfirm
      cancel-text="取消"
      ok-text="删除"
      title="是否删除?"
      @confirm="deleteFunction(toRaw(state.selectedRowKeys))"
    >
      <a-button danger>删除</a-button>
    </a-popconfirm>

    <a-button>导出</a-button>
  </a-row>
  <a-table
    :columns="columns"
    :data-source="TableData"
    :loading="loading"
    :pagination="pagination"
    :row-selection="{
      selectedRowKeys: state.selectedRowKeys,
      onChange: onSelectChange,
    }"
    @change="handleTableChange"
    style="height: calc(100vh - 278px)"
  >
    <template #bodyCell="{ column, record }">
      <template v-if="column.key === 'avatar'">
        <a-avatar :size="58" :src="proxy.baseUrl + record.avatar"> </a-avatar>
      </template>

      <template v-if="column.key === 'status'">
        <span>
          <a-tag v-if="record.status === 1" color="geekblue">正常</a-tag>
          <a-tag v-else color="error">下架</a-tag>
        </span>
      </template>
      <template v-if="column.key === 'content'">
        <p class="table-item-content">{{ record.content }}</p>
      </template>
      <template v-if="column.key === 'pub_date'">
        <span>
          {{ dayjs(record.create_time).format("YYYY-MM-DD HH:mm:ss") }}
        </span>
      </template>
      <template v-if="column.key === 'up_date'">
        <span>
          {{ dayjs(record.edit_time).format("YYYY-MM-DD HH:mm:ss") }}
        </span>
      </template>

      <template v-if="column.key === 'action'">
        <span style="display: flex; align-items: center; gap: 15px">
          <a-button type="primary" @click="addOrEdit('edit', record)">
            <template #icon>
              <EditOutlined />
            </template>
          </a-button>
          <a-popconfirm
            cancel-text="取消"
            ok-text="删除"
            title="是否删除该树洞文章?"
            @confirm="deleteFunction(record.id)"
          >
            <a-button danger>
              <template #icon>
                <DeleteOutlined />
              </template>
            </a-button>
          </a-popconfirm>
        </span>
      </template>
    </template>
  </a-table>
  <a-modal
    v-model:open="open"
    :destroyOnClose="true"
    :footer="null"
    :title="modalTitle"
    @cancel="restform"
  >
    <a-form
      ref="formRef"
      :label-col="labelCol"
      :model="formState"
      :rules="rules"
      :wrapper-col="wrapperCol"
      layout="vertical"
    >
      <a-form-item label="树洞内容" name="content">
        <a-textarea v-model:value="formState.content" :rows="4" />
      </a-form-item>
      <a-form-item label="树洞文章图片" name="images">
        <Upload v-model:FileList="formState.images" :MaxCount="8"></Upload>
      </a-form-item>
      <a-form-item :wrapper-col="{ span: 14, offset: 16 }">
        <a-button @click="restform">取消</a-button>
        <a-button style="margin-left: 10px" type="primary" @click="submit"
          >确认
        </a-button>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup>
import {
  DeleteOutlined,
  EditOutlined,
  RedoOutlined,
  SearchOutlined,
} from "@ant-design/icons-vue";
import {
  computed,
  getCurrentInstance,
  h,
  reactive,
  ref,
  toRaw,
  watch,
} from "vue";
import {
  addNewTreeHole,
  deleteTreeHole,
  editTreeHole,
  getAllList,
} from "@/api/treehole.js";
import dayjs from "dayjs";
import { userStore } from "@/store/modules/user.js";
import { message } from "ant-design-vue";
import "md-editor-v3/lib/preview.css";
import Upload from "@/components/Upload/index.vue";

const { proxy } = getCurrentInstance();
const user = userStore();
const initSearch = {
  content: "",
  time: undefined,
};
let searchInfo = reactive({ ...initSearch });

let TableData = ref([]);
// 表单
const formState = reactive({
  content: "",
  images: [],
});
const labelCol = {
  style: {
    width: "150px",
  },
};
const wrapperCol = {
  span: 24,
};

// ref
const formRef = ref();
let loading = ref(true);
const state = reactive({
  selectedRowKeys: [],
});

// 基础数据
let open = ref(false);
let total = ref(0);
let current = ref(0);
let pageSize = ref(0);
let modalTitle = ref("新增");
let editTreeId = ref(0);
// 配置规则
const rules = {
  content: [
    { required: true, message: "树洞文章内容不能为空", trigger: "change" },
  ],
};

const columns = [
  {
    title: "用户头像",
    key: "avatar",
    dataIndex: "avatar",
  },
  {
    title: "用户名",
    key: "username",
    dataIndex: "username",
    width: 100,
  },
  {
    title: "内容",
    key: "content",
    dataIndex: "content",
    width: 200,
  },
  {
    title: "点赞数",
    key: "likes",
    dataIndex: "likes",
    width: 100,
  },
  {
    title: "评论数",
    key: "total",
    dataIndex: "total",
    width: 100,
  },
  {
    title: "状态",
    key: "status",
    dataIndex: "status",
    width: 100,
  },

  {
    title: "发布时间",
    key: "pub_date",
    dataIndex: "pub_date",
    width: 300,
  },
  {
    title: "更新时间",
    key: "up_date",
    dataIndex: "up_date",
    width: 300,
  },
  {
    title: "操作",
    key: "action",
    width: 300,
  },
];

// 查询树洞文章
const search = async () => {
  loading.value = true;
  if (searchInfo.content === "" && searchInfo.time === undefined) {
    message.error("查询不能为空");
    return;
  }
  let info = toRaw(searchInfo);
  await get_TableData({ ...info });
};

// 重置查询
const restSearch = async () => {
  loading.value = true;
  Object.assign(searchInfo, initSearch);
  await get_TableData();
};

// 查询table数据
const get_TableData = async (params) => {
  loading.value = true;
  let res = await getAllList({ id: user.user_id, ...params });
  if (!res) return;
  if (res.status === 400) {
    message.error(res.data);
    return;
  }
  TableData.value = res.data.map((item) => ({ ...item, key: item.id }));
  total.value = res.total;
  current.value = res.page;
  pageSize.value = res.pageSize;
  loading.value = false;
};

// 新增和修改
const addOrEdit = async (type, data = null) => {
  if (type === "edit") modalTitle.value = "编辑";
  else modalTitle.value = "新增";
  if (data) {
    editTreeId.value = data["id"];
    formState.content = data["content"];
    formState.images = data["images"];
  }
  open.value = true;
};

// 勾选删除id
const onSelectChange = (selectedRowKeys) => {
  state.selectedRowKeys = selectedRowKeys;
};

const restform = () => {
  handeEditData({
    content: "",
    images: [],
  });
  open.value = false;
};
const handeEditData = (obj) => {
  if (obj) {
    for (let key in obj) {
      if (formState.hasOwnProperty(key)) {
        formState[key] = obj[key];
      }
    }
  }
};

// 删除
const deleteFunction = async (params) => {
  let res = await deleteTreeHole({ id: params });
  await get_TableData();
  message.success(res.data);
};

// 提交
const submit = async () => {
  formRef.value
    .validate()
    .then(async () => {
      const info = toRaw(formState);
      let res;
      if (modalTitle.value === "新增") {
        res = await addNewTreeHole({ user: user.user_id, ...info });
      } else {
        res = await editTreeHole({ TreeId: editTreeId.value, ...info });
      }
      if (res && res.status === 200) message.success(res.data);
      else message.error(res.data);
      await get_TableData();
      restform();
    })
    .catch((error) => {
      console.log("error", error);
    });
};

// 分页
const pagination = computed(() => ({
  total: total.value,
  current: current.value,
  pageSize: pageSize.value,
  showTotal: (total) => `总共 ${total} 项`,
  defaultPageSize: 10,
  pageSizeOptions: ["5", "10", "15", "20"], // 可不设置使用默认
}));
// 点击分页
const handleTableChange = (pag, filters, sorter) => {
  console.log(pag);
  get_TableData({ page: pag.current, pageSize: pag.pageSize });
};

get_TableData();
</script>

<style lang="scss" scoped>
.search {
  .btn {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-evenly;
    gap: 15px;
  }
}

.blogPreview {
  width: 100%;

  .title {
    color: #252933;
    font-size: 30px;
    text-align: center;
    font-weight: 600;
  }

  .info {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 20px;
    color: #8a919f;

    .iconBasic {
      display: inline-block;
      font-size: 16px;
      margin: 0 5px;
    }
  }

  .content {
    margin-top: 20px;
    height: calc(100vh - 150px);
    overflow-y: scroll;
    padding: 0 20px;

    .preview {
      width: 100%;
      display: grid;
      grid-template-columns: auto 300px;
      gap: 15px;
      padding: 15px;

      h1 {
        font-size: 22px;
        font-weight: 600;
        padding-bottom: 10px;
        border-bottom: 1px solid #eaeaea;
      }
    }
  }
}

.table-item-content {
  width: 200px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.topActive {
  background-color: #63a35c;
  color: #fff;
}
</style>
